<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入组织名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="手机号" prop="account">
            <el-input
              v-model="queryParams.account"
              placeholder="请输入手机号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="名称" prop="automateName">
            <el-input
              v-model="queryParams.automateName"
              placeholder="请输入自动化名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                       v-hasPermi="['smart:automate:query']"
            >搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['smart:automate:export']"
            >导出
            </el-button>
          </el-form-item>
        </el-form>
        <el-col>
          <el-table v-loading="loading" :data="automateList" border @selection-change="handleSelectionChange">
            <el-table-column label="手机号" align="center" prop="account" width="120"/>
            <el-table-column label="网关MAC" align="center" prop="gatewayMac" :show-overflow-tooltip="true" width="180"/>
            <el-table-column label="家庭名称" align="center" prop="homeName" :show-overflow-tooltip="true"/>
            <!--            <el-table-column label="网关名称" align="center" prop="gatewayName" :show-overflow-tooltip="true"/>-->
            <el-table-column label="自动化名称" align="center" prop="automateName" :show-overflow-tooltip="true"/>
            <!--            <el-table-column label="场景编号" align="center" prop="code" :show-overflow-tooltip="true"/>-->

            <!--            <el-table-column label="背景图片" align="center" prop="imgUrl" :show-overflow-tooltip="true"/>-->
            <el-table-column label="组织名称" align="center" prop="deptName" :show-overflow-tooltip="true"/>
            <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" width="180">
              <!--<template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
              </template>-->
            </el-table-column>
            <!--            <el-table-column label="修改时间" align="center" prop="modifyTime" width="180">-->
            <!--<template slot-scope="scope">
              <span>{{ parseTime(scope.row.modifyTime, '{y}-{m}-{d}') }}</span>
            </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetails(scope.row)"
                           v-hasPermi="['smart:automate:detail']"
                >详情
                </el-button>
              </template>
            </el-table-column>


          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList"
          />
        </el-col>
      </el-col>
    </el-row>

    <el-dialog :title="title" :visible.sync="detail" width="1000px" append-to-body>
      <!--      <el-descriptions title="网关信息">-->

      <!--      </el-descriptions>-->
      <!--      <gatewayDetails :row="form.gatewayMac" :column-count="3"></gatewayDetails>-->
      <!--      <el-divider/>-->
      <el-descriptions title="自动化详情" :column=3 contentClassName="my-content" labelClassName="my-label">
        <el-descriptions-item label="名称">{{ form.automateName }}</el-descriptions-item>
        <el-descriptions-item label="编号">{{ form.code }}</el-descriptions-item>
        <el-descriptions-item label="图片名称">{{ form.imgUrl }}</el-descriptions-item>
        <el-descriptions-item label="执行时段">
          <el-tag style="margin-top: -15px">{{ form.triggerTime }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ form.createTime }}</el-descriptions-item>
        <el-descriptions-item label="修改时间">{{ form.modifyTime }}</el-descriptions-item>
      </el-descriptions>
      <el-divider/>
      <el-descriptions title="执行设备"></el-descriptions>
      <template>
        <el-table v-loading="loading" :data="relationDeviceData">
          <el-table-column prop="deviceName" label="设备名称">
            <template slot-scope="scope">
              <span v-if=" scope.row.deviceName===undefined"><el-tag type="info">设备不存在</el-tag></span>
              <span v-else>{{ scope.row.deviceName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="deviceMac" label="设备MAC" width="180"></el-table-column>
          <el-table-column prop="deviceType" label="设备类型" width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.deviceType }}</span>
            </template>
          </el-table-column>
          <el-table-column label="类型名称" width="200">
            <template slot-scope="scope">
              <div class="myTagCategoryName" v-if="scope.row.defaultDeviceName">{{ scope.row.defaultDeviceName }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="deviceStatus" label="设备动作">
            <template slot-scope="scope">
              <div class="myTagLight">{{ scope.row.stateDes }}</div>
              <!--              <div v-html="smartFetchStatus(scope.row.actions2,scope.row.deviceType)">-->
              <!--              </div>-->
            </template>
          </el-table-column>
          <!--          <el-table-column prop="actions" label="设备状态">-->
          <!--            <template slot-scope="scope">-->
          <!--              <div v-html="fetchStatus(scope.row.actions,scope.row.deviceType)">-->
          <!--              </div>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detail = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改自动化(联动)对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAutomate,
  getAutomate,
  delAutomate,
  addAutomate,
  updateAutomate,
  exportAutomate
} from '@/api/system/automate'
import { deptTreeSelect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import gatewayDetails from '@/views/components/gateway/details'
import { fetchStatus } from '@/api/system/device'

export default {
  name: 'Automate',
  components: { Treeselect, gatewayDetails },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 自动化(联动)表格数据
      automateList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //是否显示详情
      detail: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        automateName: undefined,
        account: undefined,
        deptId: undefined
      },
      // 表单参数
      form: {},
      relationDeviceData: [],
      // 表单校验
      rules: {}
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
    this.getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDictDataByType('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
    this.getConfigKey('sys.user.initPassword').then(response => {
      this.initPassword = response.msgname
    })
  },
  methods: {
    fetchStatus,
    /** 查询自动化(联动)列表 */
    getList() {
      this.loading = true

      if (!this.queryParams.deptId) {
        // 取出当前用户的组织ID
        this.queryParams.deptId = this.$store.getters.deptId
      }

      listAutomate(this.queryParams).then(response => {
        this.automateList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleView(row) {
      alert('暂以此模拟具体操作')
      //this.open = true;
      //this.form = row;
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.detail = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        homeId: undefined,
        gatewayMac: undefined,
        name: undefined,
        imgUrl: undefined,
        code: undefined,
        triggerTime: undefined,
        triggerDeviceState: undefined,
        executeDeviceState: undefined,
        automateType: undefined,
        createTime: undefined,
        modifyTime: undefined,
        defendStatus: '0',
        triggerType: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加自动化(联动)'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getAutomate(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改自动化(联动)'
      })
    },
    handleDetails(row) {
      this.reset()
      const id = row.id || this.ids
      getAutomate(id).then(response => {
        this.form = response.data
        this.relationDeviceData = response.data.deviceList
        this.detail = true
        this.title = row.automateName + '详情'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateAutomate(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addAutomate(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除自动化(联动)编号为"' + ids + '"的数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delAutomate(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportAutomate(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.getList()
    }
  }
}
</script>
